import { unref, nextTick } from 'vue'

import echarts from '../plugins/echarts/index'
import { merge } from 'lodash-es'
import { remToPx } from '@/utils/common.js'
import { ToolboxComponent } from 'echarts/components';
echarts.use([ToolboxComponent]);

export function useECharts(
  elRef,
  context,
  theme = 'light',// 'light' | 'dark' | 'default' = 'light'
) {
  let chartInstance = null

  function initCharts() {
    const el = unref(elRef)
    if (!el || !unref(el)) {
      return
    }

    chartInstance = echarts.init(el, theme)
    window.addEventListener("resize", () => {
      resize();
    });
  }

  function setOptions(options, clear = true) {
    const obj = {
      tooltip: {
        renderMode: 'html',
        appendToBody: true,
        className: 'echarts-tooltip',
        textStyle: {
          color: '#FFF',
          fontSize: remToPx(0.75)
        }
      }
    }
    nextTick(() => {
      if (!chartInstance) {
        initCharts()

        if (!chartInstance) return
      }
      clear && chartInstance.clear()
      
      chartInstance.setOption(merge(options, obj))
      if(context){
        chartInstance.on('click',(events)=>{
          context.emit("chartClick", events.data)
        })
        
      }
    })
  }

  function resize() {
    chartInstance.resize()
  }

  return {
    setOptions,
    resize,
    echarts,
  }
}
